package src_2;

import java.util.Arrays;

public class SeqStack<T> {
	private int default_size=10;
	private int capacity;
	private int capacityIncrement=0;
	private Object[] elementData;
	private int size=0;
	
	public  SeqStack() {
		capacity=default_size;
		elementData=new Object[capacity];
		
	}
	
	public  SeqStack(T element,int initSize) {
		this.capacity=initSize;
		elementData=new Object[capacity];
		elementData[0]=element;
		size++;
		
	}
	
	public SeqStack(T element,int initSize,int capacityIncrement) {
		this.capacity=initSize;
		this.capacityIncrement=capacityIncrement;
		elementData=new Object[capacity];
		elementData[0]=element;
		size++;
	}
	
	public int length() {
		return size;
	}
	public void push(T element) {
		ensureCapacity(size+1);
		elementData[size++]=element;
	}
	
	private void ensureCapacity(int minCapacity) {
		if(minCapacity>capacity) {
			if(capacityIncrement>0) {
				while(capacity<minCapacity) {
					capacity+=capacityIncrement;
				}
			}else {
				while(capacity<minCapacity) {
					capacity<<=1;
				}
			}
		}
		elementData=Arrays.copyOf(elementData, capacity);
	}//拓展数组大小
	
	@SuppressWarnings("unchecked")
	public T pop() {
		T oldValue=(T)elementData[size-1];
		elementData[--size]=null;
		return oldValue;
	}//出栈
	
	@SuppressWarnings("unchecked")
	public T peek() {
		return (T)elementData[size-1];
	}
	
	public boolean empty() {
		return size==0;
	}//判断顺序栈是否为空
	
	public void clear() {
		Arrays.fill(elementData, null);
		size=0;
	}//清空顺序栈
	
	public String tString() {
		if(size==0) {
			return "[]";
		}else {
			StringBuilder sBuilder=new StringBuilder("[");
			for(int i=size-1;i>=-1;i--) {
				sBuilder.append(elementData[i].toString()+",");
			}
			int len=sBuilder.length();
			return sBuilder.delete(len-1, len).append("]").toString();
		}
	}

}
